package org.finesys.common.log.trace.processor;

import org.aopalliance.intercept.MethodInvocation;
import org.finesys.common.log.trace.interceptor.redis.SpringRedisCommandInterceptor;
import org.finesys.common.log.trace.util.ProxyUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * redis连接
 */
public class SpringRedisConnectionFactoryPostProcessor implements BeanPostProcessor {

    private static final String GET_CONNECTION = "getConnection";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RedisConnectionFactory) {
            return ProxyUtil.getProxy(bean, this::interceptorRedisFactory);
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    private Object interceptorRedisFactory(MethodInvocation methodInvocation) throws Throwable {
        Object result = methodInvocation.proceed();
        if (GET_CONNECTION.equals(methodInvocation.getMethod().getName())) {
            return ProxyUtil.getProxy(result, new SpringRedisCommandInterceptor());
        }
        return result;
    }
}
